<template>
  <div class="transaction-list">
    <div class="transaction-header">
      <button @click="fetchTransactions" class="refresh-button" >刷新</button>
    </div>
    <SimpleTable :columns="columns" :data="formattedRecords" style="width: 800px; margin-bottom: 20px" />
    <n-pagination
      v-model:page="currentPage"
      :page-size="pageSize"
      :item-count="totalRecords"
      show-size-picker
      @update:page="fetchTransactions"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, computed } from 'vue';
import { NPagination, useMessage } from 'naive-ui';
import apiClient from '@/api/axios';
import { useAuthStore } from '@/stores/auth';
import { useRouter } from 'vue-router';
import SimpleTable from '@/components/user/userDashboard/SimpleTable.vue';

export default defineComponent({
  components: {
    SimpleTable,
    NPagination,
  },
  setup() {
    const records = ref([]); // 确保初始化为数组
    const totalRecords = ref(0); // 用于存储记录总数
    const currentPage = ref(1);
    const pageSize = ref(10);

    const message = useMessage();
    const authStore = useAuthStore();
    const router = useRouter();

    /**
     * 拉取积分变动记录
     */
    const fetchTransactions = async () => {
      try {
        const response = await apiClient.post('/point/pointtransaction/page/my', {
          current: currentPage.value,
          size: pageSize.value,
        });

        if (response.data.code === 0) {
          records.value = response.data.data.records || []; // 确保赋值为数组
          totalRecords.value = response.data.data.total || 0;
          message.success('拉取积分变动记录成功');
        } else if (response.data.code === 40000) {
          message.error('未登录');
          authStore.logout();
          await router.push('/user/login');
        } else {
          message.error('获取积分变动记录失败');
        }
      } catch (error) {
        message.error('请求失败，请稍后再试');
        console.error('Fetch Transactions Error:', error);
      }
    };

    watch([currentPage, pageSize], fetchTransactions);

    // 初始化时加载数据
    fetchTransactions();

    const formattedRecords = computed(() => {
      return records.value.map((record) => {
        const changeAmount = parseFloat(record.changeAmount);
        return {
          ...record,
          changeAmountHtml: `<span style="color:${changeAmount > 0 ? 'green' : 'red'}; font-weight: bold;">${changeAmount > 0 ? '+' : ''}${changeAmount}</span>`
        };
      });
    });

    const columns = [
      {
        title: '订单ID',
        key: 'id',
      },
      {
        title: '变动金额',
        key: 'changeAmountHtml',
        render(row) {
          return row.changeAmountHtml;
        },
      },
      {
        title: '描述',
        key: 'description',
      },
      {
        title: '时间',
        key: 'createTime',
      },
    ];

    return {
      records, // 原始记录
      formattedRecords, // 格式化后的记录，绑定给表格
      totalRecords,
      currentPage,
      pageSize,
      columns,
      fetchTransactions,
    };
  },
});
</script>

<style scoped>
.transaction-list {
  margin-top: 20px;
}

.transaction-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.refresh-button {
  padding: 5px 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.refresh-button:hover {
  background-color: #45a049;
}
</style>
